package org.apache.lucene.ocean;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

public class MemoryIndexThreadLocal {
  private Map<IndexID,WriteableMemoryIndex> map = new HashMap<IndexID,WriteableMemoryIndex>();
  private Map<Thread,WriteableMemoryIndex> threadMap = new HashMap<Thread,WriteableMemoryIndex>();
  private TransactionSystem transactionSystem;

  public MemoryIndexThreadLocal(TransactionSystem transactionSystem) {
    this.transactionSystem = transactionSystem;
  }
  
  public WriteableMemoryIndex get() throws Exception {
    Thread thread = Thread.currentThread();
    WriteableMemoryIndex index = threadMap.get(thread);
    if (index == null) {
      index = transactionSystem.newWriteableMemoryIndex();
      index.createIndexSnapshot(new Long(1));
      map.put(index.getId(), index);
      threadMap.put(thread, index);
    }
    return index;
  }
  
  public void remove(IndexID indexId) {
    map.remove(indexId);
    threadMap.remove(indexId);
  }

  public Collection<WriteableMemoryIndex> getAll() {
    return map.values();
  }
}
